<?php

date_default_timezone_set('America/Recife');

require 'config.php';
require 'inc/db.php';
require 'inc/functions.php';
require 'inc/config.php';
require_once 'inc/changes.php';
require_once 'inc/config_dao.php';
require_once 'inc/netcontrol_ctl.php';
require_once 'inc/user_dao.php';
require_once 'inc/contract_dao.php';
require_once 'inc/client_dao.php';

$config = config::get_instance();
$timestamp_now = date('YmdHis');
$timestamp_log = date('Y-m-d H:i:s');
$timestamp_timeout = date('YmdHis', mktime(date(H)-1));
$arp = arp();

$client_dao = new client_dao();
$contract_dao = new contract_dao();
$contracts = $contract_dao->fetch_all();

foreach ($contracts as $contract) {
//	exec('echo "'.$timestamp_log.': Contract - Username: '.$contract->client_username.' - IP: '.$contract->ip.' - MAC: '.$contract->mac.'" >> /var/log/vulpes.log');
	$client_found = false;
	foreach ($arp as $row) {
//		exec('echo "'.$timestamp_now.': ARP - IP: '.$row['ip_address'].' - MAC: '.$row['hw_address'].'" >> /var/log/vulpes.log');
		if ($row['ip_address'] == $contract->ip && strtoupper($row['hw_address']) == strtoupper($contract->mac) && $contract->status == 'L') {
			$contract->last_access = $timestamp_now;
			$client_dao->update_timestamp($contract->client_id);
			exec('echo "'.$timestamp_log.': Found client '.$contract->client_username.' in ARP. Updated timestamp." >> /var/log/vulpes.log');
			$client_found = true;
		}
	}
//	if (!$client_found) {
//		exec('echo "'.$timestamp_log.': Couldn\'t find client '.$contract->client_username.' in ARP." >> /var/log/vulpes.log');
//	}

	if ($timestamp_timeout > $contract->last_access && $contract->active) {
		exec('echo "'.$timestamp_log.': Disactivating '.$contract->client_username.' ('.$contract->last_access.' < '.$timestamp_timeout.')" >> /var/log/vulpes.log');
		$client_dao->disactivate($contract->client_id);
	}
}

$netcontrol = new netcontrol_ctl();
$netcontrol->refresh_iptables();
$netcontrol->refresh_tc();

?>
